<?php
if (!isset($_SESSION)) session_start();
include "functions.php";
include "constants.php";
$token = $_POST['token'];
if(!$token){
?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html>
	<head>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script>
	try{
		hash = window.location.hash.replace('#access_token=', '');
		if(hash.indexOf('&') != -1){
			arrHash = hash.split('&');
			$.ajax({
		        url: '<?php echo BASE_URL ?>/oauth.php',
		        data: {"token" : arrHash[0]},
		        type: 'POST',
		        success: function(responseText){  
		            if(responseText === '1'){
		            	window.opener.location.href='<?php echo BASE_URL ?>';
						window.close();
					}
		        }
		    });
		}
	}
	catch(e){
		alert(e);
	}
	</script>
	</head>
	<body></body>
	</html>
<?php
	die;
}

$graphApiUser = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$token;
$response = cURL($graphApiUser);
if($response){
	$userData = json_decode($response, true);
	if(!empty($userData) && $userData['id']){
		if($userData['gender'] == 'male' || $userData['gender'] == 'female' ){
			$gender = strtoupper($userData['gender']);
		}
		else{
			$gender = '';
		}
		$params = array(
			'user_social_id'	=>	$userData['id'],
			'user_email'		=>	$userData['email'],
			'user_fullname'		=>	$userData['name'],
			'user_sso'			=>	'GPLUS',
			'user_gender'		=>	$gender,
			'user_sso_rawdata'	=>	mysql_real_escape_string(json_encode($userData))
		);
		$sqlInsert = sqlInsertString($params, 'users');
		$i = 1;
		$sep = "";
		$sqlUpdate = "";
		$count = count($params);
		foreach($params as $field => $value){
			if($i < $count){
				$sep = ', ';
			}
			else{
				$sep = '';
			}
			$sqlUpdate .= "`$field` = '$value'".$sep;
			
			$i++;
		}
		$sqlInsert = $sqlInsert . " ON DUPLICATE KEY UPDATE " . $sqlUpdate;

		if(mysql_query($sqlInsert)){
			$sqlInfo = "SELECT user_id, user_fullname FROM users WHERE user_social_id='".$params['user_social_id']."'";
			$query = mysql_query($sqlInfo);
			$userInfo = mysql_fetch_array($query);

			$_SESSION['user'] = array(
				'id'	=>	$userInfo['user_id'],
				'name'	=>	$userInfo['user_fullname'],
				);
			$_SESSION['sso'] = 'GPLUS';
			$_SESSION['token'] = $token;
			echo '1';
		}
		else{
			echo '0';
		}
	}
}
die;